package com.tange.ai.iot.client.gnssa.token;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.util.Consumer;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.tange.ai.iot.client.gnssa.R;
import com.tange.ai.iot.client.gnssa.bean.LoginBean;
import com.tange.ai.iot.client.gnssa.bean.RespMsg;
import com.tange.ai.iot.client.gnssa.home.HomeActivity;
import com.tange.ai.iot.client.gnssa.httpservice.DeviceService;
import com.tange.ai.iot.client.gnssa.internal.DispatchActivity;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.core.access.token.Authentication;
import com.tange.core.access.token.Token;
import com.tange.core.data.structure.Resp;

import java.util.HashMap;

import base.activity.BaseActivity;
import base.http.rxandroid.CustomDisposableForJava;
import base.http.utils.RetrofitManager;
import base.utils.LogUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class XqAccountLoginActivity extends BaseActivity {


    private TextView accountType;
    private EditText username;
    private EditText password;
    private TextView loginTest;
    private ProgressBar loading;
    private ConstraintLayout container;
    DeviceService deviceService = new RetrofitManager().getDefaultClient(DeviceService.class);

    @Override
    protected int getLayoutId() {
        return R.layout.activity_xq_account_login;
    }

    @Override
    protected void initData() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarDarkFont(true).init();

        accountType = findViewById(R.id.account_type);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        loginTest = findViewById(R.id.login_test);
        loading = findViewById(R.id.loading);
        container = findViewById(R.id.container);

        accountType.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                readyGo(DispatchActivity.class);
                return false;
            }
        });

//        if (!TextUtils.isEmpty(PreferenceUtil.getString(mContext,PRE_TOKEN))){
//            Authentication.configure(PreferenceUtil.getString(mContext,PRE_TOKEN), new Consumer<Resp<Token>>() {
//                @Override
//                public void accept(Resp<Token> tokenResp) {
//                    if(tokenResp.getSuccess() && tokenResp.getData()!=null){
//                        readyGo(HomeActivity.class);
//                    }else{
//                        showShortToast("用户令牌校验失败");
//                    }
//                }
//            });
//        }

        loginTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(username.getText().toString())) {
                    ToastUtils.showShort("请输入账号");
                    return;
                }
                if (TextUtils.isEmpty(password.getText().toString())) {
                    ToastUtils.showShort("请输入密码");
                    return;
                }
                HashMap<String, Object> params = new HashMap<>();
                params.put("userName", username.getText().toString().trim());
                params.put("password", password.getText().toString().trim());

                deviceService.postAccountLogin(params)
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new CustomDisposableForJava<RespMsg<LoginBean>>(mContext) {
                            @Override
                            public void onNext(RespMsg<LoginBean> bean) {
                                try {
                                    super.onNext(bean);
                                    LogUtil.INSTANCE.e("http:" + GsonUtils.toJson(bean));
                                    if (bean.code.equals("200")) {
                                        showShortToast("登录成功");
                                        if (!TextUtils.isEmpty(bean.data.token)) {
                                            PreferenceUtil.setString(mContext, InternalAccountLoginActivity.PRE_AREA_CODE, "86");
                                            PreferenceUtil.setString(mContext, InternalAccountLoginActivity.PRE_USER_NAME, username.getText().toString().trim());
                                            PreferenceUtil.setString(mContext, InternalAccountLoginActivity.PRE_USER_PWD, password.getText().toString().trim());
                                            PreferenceUtil.setString(mContext, InternalAccountLoginActivity.TANGE_TOKEN, bean.data.tangeToken.access_token);

                                            SPUtils.getInstance().put(InternalAccountLoginActivity.PRE_TOKEN, bean.data.token);

                                            Authentication.configure(bean.data.tangeToken.access_token, new Consumer<Resp<Token>>() {
                                                @Override
                                                public void accept(Resp<Token> tokenResp) {
                                                    if (tokenResp.getSuccess() && tokenResp.getData() != null) {
                                                        readyGo(HomeActivity.class);
                                                    } else {
                                                        showShortToast("用户令牌校验失败");
                                                    }
                                                }
                                            });
                                        }
                                    } else {
                                        showShortToast("登录失败");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    showShortToast("登录失败");
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                LogUtil.INSTANCE.e(e + "");
                                showShortToast("登录失败");
                            }
                        });
            }
        });

        if (!TextUtils.isEmpty(PreferenceUtil.getString(mContext, InternalAccountLoginActivity.TANGE_TOKEN))) {
            Authentication.configure(PreferenceUtil.getString(mContext, InternalAccountLoginActivity.TANGE_TOKEN), new Consumer<Resp<Token>>() {
                @Override
                public void accept(Resp<Token> tokenResp) {
                    if (tokenResp.getSuccess() && tokenResp.getData() != null) {
                        readyGo(HomeActivity.class);
                    } else {
                        loginTest.performClick();
                    }
                }
            });
        }else{
            loginTest.performClick();
        }

    }

}
